import Vue from 'vue'
import Vuex from 'vuex'
import {
  setToken,
  getToken,
  removeToken,
  setLocalArticleID
} from '@/utils/auth'
import { userInfoAPI } from '@/api'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    tokenObj: getToken() || {},
    userInfo: {},
    articleInfo: {},
    articleID: ''
  },
  mutations: {
    changeTokenObj (state, obj) {
      state.tokenObj = obj
      setToken(obj)
    },
    changeUserInfo (state, obj) {
      state.userInfo = obj
    },
    logout (state) {
      state.tokenObj = {}
      removeToken()
    },
    setArticleInfo (state, obj) {
      state.articleInfo = obj
    },
    setArticleID (state, id) {
      state.articleID = id
      setLocalArticleID(id)
    }
  },
  actions: {
    async getUserInfo (context) {
      if (!context.state.userInfo.name) {
        const res = await userInfoAPI()
        context.commit('changeUserInfo', res.data.data)
      }
    }
  }
})
